<template>
  <el-container>
    <el-header class="header">
      <h1>书架</h1>
    </el-header>
    <el-main class="main">
      <el-row :gutter="20">
        <el-col :span="8" v-for="book in books" :key="book.idbook">
          <el-card class="card">
            <h3 @click="viewBook(book.idbook)">{{ book.bookName }}</h3>
            <p>作者: {{ book.penName }}</p>
            <p>点击次数: {{ book.clicks }}</p>
            <el-button type="danger" @click="removeFromBookshelf(book.idbook)">移出书架</el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      books: []
    };
  },
  created() {
    this.fetchBookshelf();
  },
  methods: {
    async fetchBookshelf() {
      try {
        const token = localStorage.getItem('accessToken');
        const userResponse = await axios.get('/api/users/me', {
          headers: { Authorization: `Bearer ${token}` }
        });
        const iduser = userResponse.data.iduser;
        const bookshelfResponse = await axios.get(`/api/bookshelf/${iduser}`);
        const bookIds = bookshelfResponse.data.map(item => item.idbook);
        if (bookIds.length > 0) {
          this.fetchBooks(bookIds);
        } else {
          this.books = [];
        }
      } catch (error) {
        console.error('获取书架失败:', error);
        this.$message.error('获取书架失败');
      }
    },
    async fetchBooks(bookIds) {
      try {
        const response = await axios.post('/api/books/batch', bookIds);
        this.books = response.data;
      } catch (error) {
        console.error('获取书籍信息失败:', error);
        this.$message.error('获取书籍信息失败');
      }
    },
    viewBook(idbook) {
      this.$router.push({ path: `/read/${idbook}` });
    },
    async removeFromBookshelf(idbook) {
      try {
        const token = localStorage.getItem('accessToken');
        const userResponse = await axios.get('/api/users/me', {
          headers: { Authorization: `Bearer ${token}` }
        });
        const iduser = userResponse.data.iduser;
        await axios.delete('/api/bookshelf', { params: { iduser, idbook } });
        this.books = this.books.filter(book => book.idbook !== idbook);
        this.$message.success('已移出书架');
      } catch (error) {
        console.error('移出书架失败:', error);
        this.$message.error('移出书架失败');
      }
    }
  }
};
</script>

<style scoped>
body {
  background-color: #e6ffe6; /* 浅绿色背景 */
  font-family: 'Microsoft YaHei', sans-serif; /* 微软雅黑字体 */
}

.header {
  background-color: #218838;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  font-size: 24px;
  border-bottom: none;
}

.main {
  padding: 20px;
}

.el-button {
  margin-top: 10px;
}

.el-card {
  opacity: 0.9; /* 设置不透明度为90% */
}

h3 {
  cursor: pointer;
  color: #28a745; /* 绿色 */
}

h3:hover {
  text-decoration: underline;
}
</style>
